<template>
  <div class="assignments-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2>作业管理</h2>
        <el-button type="primary" @click="showCreateDialog = true" v-if="isTeacher">
          <el-icon><Plus /></el-icon>
          创建作业
        </el-button>
      </div>
    </el-card>

    <!-- 作业列表 -->
    <el-card class="assignments-list">
      <template #header>
        <div class="card-header">
          <span>我的作业</span>
          <el-button text @click="loadAssignments">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table :data="assignments" v-loading="loading" style="width: 100%">
        <el-table-column prop="title" label="作业标题" min-width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="viewAssignmentDetail(row)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="class_name" label="班级" min-width="120" />
        <el-table-column prop="due_date" label="截止时间" width="180">
          <template #default="{ row }">
            <el-tag :type="isExpired(row.due_date) ? 'danger' : 'success'">
              {{ formatDate(row.due_date) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_score" label="总分" width="80" align="center" />
        <el-table-column prop="submission_count" label="提交数" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.submission_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" v-if="isTeacher">
          <template #default="{ row }">
            <el-button size="small" @click="viewAssignmentDetail(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editAssignment(row)">编辑</el-button>
            <el-button size="small" type="success" @click="viewSubmissions(row)">查看提交</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="assignments.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无作业数据" />
      </div>
    </el-card>

    <!-- 创建作业对话框 -->
    <el-dialog v-model="showCreateDialog" title="作业布置" width="900px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="120px">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="作业标题" prop="title">
                <el-input v-model="createForm.title" placeholder="请输入作业标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择班级" prop="class_id">
                <el-select v-model="createForm.class_id" placeholder="请选择班级" style="width: 100%">
                  <el-option
                    v-for="classItem in classes"
                    :key="classItem.id"
                    :label="classItem.name"
                    :value="classItem.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="作业描述" prop="description">
            <el-input 
              v-model="createForm.description" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入作业描述，支持富文本格式"
            />
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="截止时间" prop="due_date">
                <el-date-picker
                  v-model="createForm.due_date"
                  type="datetime"
                  placeholder="选择截止时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总分" prop="total_score">
                <el-input-number v-model="createForm.total_score" :min="1" :max="100" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 题目选择方式 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Collection /></el-icon>
              <span>题目选择</span>
            </div>
          </template>
          
          <el-radio-group v-model="createForm.selectionMethod" @change="handleSelectionMethodChange">
            <el-radio label="manual">手工选题</el-radio>
            <el-radio label="auto">自动选题</el-radio>
          </el-radio-group>
          
          <!-- 手工选题 -->
          <div v-if="createForm.selectionMethod === 'manual'" class="selection-content">
            <el-form-item label="选择题目" prop="problem_ids">
              <el-select 
                v-model="createForm.problem_ids" 
                multiple 
                placeholder="请选择题目" 
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="problem in problems"
                  :key="problem.id"
                  :label="`${problem.title} (${problem.difficulty})`"
                  :value="problem.id"
                >
                  <div class="problem-option">
                    <span>{{ problem.title }}</span>
                    <el-tag size="small" :type="getDifficultyType(problem.difficulty)">
                      {{ problem.difficulty }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            
            <!-- 已选题目列表 -->
            <div v-if="createForm.problem_ids.length > 0" class="selected-problems">
              <h4>已选题目 ({{ createForm.problem_ids.length }})</h4>
              <el-table :data="selectedProblems" size="small">
                <el-table-column prop="title" label="题目" />
                <el-table-column prop="difficulty" label="难度" width="80">
                  <template #default="{ row }">
                    <el-tag size="small" :type="getDifficultyType(row.difficulty)">
                      {{ row.difficulty }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="points" label="分值" width="80" />
                <el-table-column label="操作" width="80">
                  <template #default="{ row }">
                    <el-button size="small" type="danger" @click="removeProblem(row.id)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          
          <!-- 自动选题 -->
          <div v-if="createForm.selectionMethod === 'auto'" class="selection-content">
            <el-form :model="autoSelectionForm" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="题目数量" prop="questionCount">
                    <el-input-number 
                      v-model="autoSelectionForm.questionCount" 
                      :min="1" 
                      :max="20" 
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="题目类型" prop="questionTypes">
                    <el-checkbox-group v-model="autoSelectionForm.questionTypes">
                      <el-checkbox label="choice">单选题</el-checkbox>
                      <el-checkbox label="blank">填空题</el-checkbox>
                      <el-checkbox label="short">简答题</el-checkbox>
                      <el-checkbox label="code">编程题</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="标签范围" prop="tagRange">
                <el-input 
                  v-model="autoSelectionForm.tagRange" 
                  placeholder="根据标签划定题目范围，多个标签用逗号分隔"
                />
              </el-form-item>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="知识点分布" prop="knowledgePoints">
                    <el-select 
                      v-model="autoSelectionForm.knowledgePoints" 
                      multiple 
                      placeholder="选择知识点，可多选"
                      style="width: 100%"
                    >
                      <el-option label="基础语法" value="basic" />
                      <el-option label="数据结构" value="data_structure" />
                      <el-option label="算法" value="algorithm" />
                      <el-option label="面向对象" value="oop" />
                      <el-option label="文件操作" value="file" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="章节分布" prop="chapters">
                    <el-select 
                      v-model="autoSelectionForm.chapters" 
                      multiple 
                      placeholder="选择章节，可多选"
                      style="width: 100%"
                    >
                      <el-option label="第一章" value="chapter1" />
                      <el-option label="第二章" value="chapter2" />
                      <el-option label="第三章" value="chapter3" />
                      <el-option label="第四章" value="chapter4" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="难度分布" prop="difficultyDistribution">
                <el-radio-group v-model="autoSelectionForm.difficultyDistribution">
                  <el-radio label="even">均匀分布</el-radio>
                  <el-radio label="random">随机分布</el-radio>
                  <el-radio label="manual">手工指定</el-radio>
                </el-radio-group>
                <div class="form-tip">
                  如果没有为题目设置难度，注意选择随机分布
                </div>
              </el-form-item>
              
              <el-form-item label="使用频度" prop="usageFrequency">
                <el-radio-group v-model="autoSelectionForm.usageFrequency">
                  <el-radio label="least">最少被使用</el-radio>
                  <el-radio label="frequent">经常被使用</el-radio>
                  <el-radio label="none">不设定</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="generateQuestions" :loading="generating">
                  <el-icon><StarFilled /></el-icon>
                  出题&预览
                </el-button>
              </el-form-item>
            </el-form>
            
            <!-- 自动生成的题目预览 -->
            <div v-if="autoGeneratedProblems.length > 0" class="auto-generated-preview">
              <h4>自动生成题目预览 ({{ autoGeneratedProblems.length }})</h4>
              <el-table :data="autoGeneratedProblems" size="small">
                <el-table-column prop="title" label="题目" />
                <el-table-column prop="type" label="类型" width="80">
                  <template #default="{ row }">
                    <el-tag size="small" :type="getQuestionTypeType(row.type)">
                      {{ getQuestionTypeText(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="difficulty" label="难度" width="80">
                  <template #default="{ row }">
                    <el-tag size="small" :type="getDifficultyType(row.difficulty)">
                      {{ row.difficulty }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="points" label="分值" width="80" />
                <el-table-column label="操作" width="80">
                  <template #default="{ row }">
                    <el-button size="small" type="danger" @click="removeAutoProblem(row.id)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <!-- 显示设置 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Setting /></el-icon>
              <span>显示设置</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="显示答案">
                <el-switch v-model="createForm.showAnswer" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="允许重做">
                <el-switch v-model="createForm.allowRetry" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="显示解析">
                <el-switch v-model="createForm.showExplanation" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="随机排序">
                <el-switch v-model="createForm.randomOrder" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createAssignment" :loading="creating">创建作业</el-button>
      </template>
    </el-dialog>

    <!-- 编辑作业对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑作业" width="600px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="作业描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="请输入作业描述" />
        </el-form-item>
        <el-form-item label="选择题目" prop="problem_ids">
          <el-select v-model="editForm.problem_ids" multiple placeholder="请选择题目" style="width: 100%">
            <el-option
              v-for="problem in problems"
              :key="problem.id"
              :label="problem.title"
              :value="problem.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="due_date">
          <el-date-picker
            v-model="editForm.due_date"
            type="datetime"
            placeholder="选择截止时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总分" prop="total_score">
          <el-input-number v-model="editForm.total_score" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="活跃" value="active" />
            <el-option label="暂停" value="paused" />
            <el-option label="结束" value="ended" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateAssignment" :loading="updating">更新</el-button>
      </template>
    </el-dialog>

    <!-- 查看提交对话框 -->
    <el-dialog v-model="showSubmissionsDialog" title="查看提交" width="800px">
      <el-table :data="submissions" style="width: 100%">
        <el-table-column prop="student_name" label="学生姓名" />
        <el-table-column prop="submitted_at" label="提交时间" />
        <el-table-column prop="score" label="得分" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" @click="gradeSubmission(row)">批改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 批改对话框 -->
    <el-dialog v-model="showGradeDialog" title="批改作业" width="500px">
      <div v-if="currentSubmission">
        <el-form ref="gradeFormRef" label-width="100px">
          <el-form-item label="学生姓名">
            <span>{{ currentSubmission.student_name }}</span>
          </el-form-item>
          <el-form-item label="提交时间">
            <span>{{ formatDate(currentSubmission.submitted_at) }}</span>
          </el-form-item>
          <el-form-item label="得分">
            <el-input-number v-model="gradeForm.score" :min="0" :max="100" />
          </el-form-item>
          <el-form-item label="反馈">
            <el-input
              v-model="gradeForm.feedback"
              type="textarea"
              :rows="4"
              placeholder="请输入批改反馈"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showGradeDialog = false">取消</el-button>
        <el-button type="primary" @click="submitGrade" :loading="grading">提交批改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Refresh, Document, Collection, Setting, StarFilled } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { assignmentsApi } from '@/api/assignments'
import { classesApi } from '@/api/classes'
import { problemsApi } from '@/api/problems'

const authStore = useAuthStore()
const isTeacher = computed(() => authStore.user?.role === 'teacher')

// 数据
const assignments = ref<any[]>([])
const classes = ref<any[]>([])
const problems = ref<any[]>([])
const submissions = ref<any[]>([])
const loading = ref(false)
const creating = ref(false)
const updating = ref(false)
const grading = ref(false)

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showSubmissionsDialog = ref(false)
const showGradeDialog = ref(false)

// 表单数据
const createForm = ref({
  title: '',
  description: '',
  class_id: 0,
  problem_ids: [],
  due_date: '',
  total_score: 100,
  selectionMethod: 'manual', // 题目选择方式：manual-手工选题，auto-自动选题
  showAnswer: false,
  allowRetry: true,
  showExplanation: true,
  randomOrder: false
})

// 自动选题表单数据
const autoSelectionForm = ref({
  questionCount: 5,
  questionTypes: ['code'],
  tagRange: '',
  knowledgePoints: [],
  chapters: [],
  difficultyDistribution: 'even',
  usageFrequency: 'least'
})

// 自动生成的题目
const autoGeneratedProblems = ref<any[]>([])
const generating = ref(false)

const editForm = ref({
  title: '',
  description: '',
  problem_ids: [],
  due_date: '',
  total_score: 100,
  status: 'active'
})
const currentAssignment = ref<any>(null)
const currentSubmission = ref<any>(null)
const gradeForm = ref({
  score: 0,
  feedback: ''
})

// 表单规则
const createRules = {
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  class_id: [{ required: true, message: '请选择班级', trigger: 'change' }],
  due_date: [{ required: true, message: '请选择截止时间', trigger: 'change' }]
}

const editRules = {
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }]
}

// 表单引用
const createFormRef = ref()
const editFormRef = ref()
const gradeFormRef = ref()

// 加载作业列表
const loadAssignments = async () => {
  loading.value = true
  try {
    const response = await assignmentsApi.getAssignments()
    assignments.value = response
  } catch (error: any) {
    console.error('加载作业列表失败:', error)
    ElMessage.error('加载作业列表失败')
  } finally {
    loading.value = false
  }
}

// 加载班级列表
const loadClasses = async () => {
  try {
    const response = await classesApi.getClasses()
    classes.value = response
  } catch (error: any) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('加载班级列表失败')
  }
}

// 加载题目列表
const loadProblems = async () => {
  try {
    const response = await problemsApi.getProblems()
    problems.value = response.problems
  } catch (error: any) {
    console.error('加载题目列表失败:', error)
    ElMessage.error('加载题目列表失败')
  }
}

// 创建作业
const createAssignment = async () => {
  if (!createFormRef.value) return
  
  await createFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 验证题目选择
      if (createForm.value.selectionMethod === 'manual' && createForm.value.problem_ids.length === 0) {
        ElMessage.warning('请至少选择一个题目')
        return
      }
      
      if (createForm.value.selectionMethod === 'auto' && autoGeneratedProblems.value.length === 0) {
        ElMessage.warning('请先生成题目')
        return
      }
      
              creating.value = true
        try {
          // 根据选择方式确定题目ID
          let problemIds = []
          if (createForm.value.selectionMethod === 'manual') {
            problemIds = createForm.value.problem_ids
          } else {
            problemIds = autoGeneratedProblems.value.map(p => p.id)
          }
          
          // 准备创建作业的数据
          const assignmentData = {
            title: createForm.value.title,
            description: createForm.value.description,
            class_id: createForm.value.class_id,
            problem_ids: problemIds,
            due_date: createForm.value.due_date ? createForm.value.due_date.toISOString() : null,
            total_score: createForm.value.total_score
          }
          
          // 调用API创建作业
          const response = await assignmentsApi.createAssignment(assignmentData)
          ElMessage.success('创建作业成功')
          showCreateDialog.value = false
          
          // 重置表单
          createForm.value = {
            title: '',
            description: '',
            class_id: 0,
            problem_ids: [],
            due_date: '',
            total_score: 100,
            selectionMethod: 'manual',
            showAnswer: false,
            allowRetry: true,
            showExplanation: true,
            randomOrder: false
          }
          
          // 重置自动选题表单
          autoSelectionForm.value = {
            questionCount: 5,
            questionTypes: ['code'],
            tagRange: '',
            knowledgePoints: [],
            chapters: [],
            difficultyDistribution: 'even',
            usageFrequency: 'least'
          }
          
          autoGeneratedProblems.value = []
          loadAssignments()
        } catch (error: any) {
          console.error('创建作业失败:', error)
          ElMessage.error('创建作业失败')
        } finally {
          creating.value = false
        }
    }
  })
}

// 编辑作业
const editAssignment = (assignment: any) => {
  editForm.value = {
    title: assignment.title,
    description: assignment.description,
    problem_ids: [],
    due_date: assignment.due_date,
    total_score: assignment.total_score,
    status: assignment.status
  }
  currentAssignment.value = assignment
  showEditDialog.value = true
}

// 更新作业
const updateAssignment = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      updating.value = true
      try {
        // 模拟更新
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success('更新作业成功')
        showEditDialog.value = false
        loadAssignments()
      } catch (error: any) {
        ElMessage.error('更新作业失败')
      } finally {
        updating.value = false
      }
    }
  })
}

// 查看作业详情
const viewAssignmentDetail = (assignment: any) => {
  ElMessage.info(`查看作业: ${assignment.title}`)
}

// 查看提交
const viewSubmissions = (assignment: any) => {
  // 模拟加载提交数据
  submissions.value = [
    {
      id: 1,
      student_name: '张三',
      submitted_at: '2024-01-18 15:30:00',
      score: 85,
      status: '已批改'
    },
    {
      id: 2,
      student_name: '李四',
      submitted_at: '2024-01-19 10:20:00',
      score: 92,
      status: '已批改'
    }
  ]
  showSubmissionsDialog.value = true
}

// 批改提交
const gradeSubmission = (submission: any) => {
  currentSubmission.value = submission
  gradeForm.value = {
    score: submission.score || 0,
    feedback: ''
  }
  showGradeDialog.value = true
}

// 提交批改
const submitGrade = async () => {
  grading.value = true
  try {
    // 模拟提交批改
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('批改提交成功')
    showGradeDialog.value = false
  } catch (error: any) {
    ElMessage.error('批改提交失败')
  } finally {
    grading.value = false
  }
}

// 工具函数
const isExpired = (dueDate: string) => {
  return new Date(dueDate) < new Date()
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'success',
    paused: 'warning',
    ended: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '活跃',
    paused: '暂停',
    ended: '结束'
  }
  return statusMap[status] || status
}

// 计算属性：已选题目
const selectedProblems = computed(() => {
  return problems.value.filter(problem => createForm.value.problem_ids.includes(problem.id))
})

// 题目选择方式变化处理
const handleSelectionMethodChange = (method: string) => {
  if (method === 'auto') {
    // 切换到自动选题时，清空手工选择的题目
    createForm.value.problem_ids = []
  }
}

// 移除手工选择的题目
const removeProblem = (problemId: number) => {
  const index = createForm.value.problem_ids.indexOf(problemId)
  if (index > -1) {
    createForm.value.problem_ids.splice(index, 1)
  }
}

// 移除自动生成的题目
const removeAutoProblem = (problemId: number) => {
  const index = autoGeneratedProblems.value.findIndex(p => p.id === problemId)
  if (index > -1) {
    autoGeneratedProblems.value.splice(index, 1)
  }
}

// 生成题目
const generateQuestions = async () => {
  generating.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟生成的题目数据
    const mockProblems = [
      {
        id: 101,
        title: '两数之和',
        type: 'code',
        difficulty: 'easy',
        points: 10
      },
      {
        id: 102,
        title: '反转字符串',
        type: 'code',
        difficulty: 'easy',
        points: 10
      },
      {
        id: 103,
        title: 'Python基础语法',
        type: 'choice',
        difficulty: 'easy',
        points: 5
      },
      {
        id: 104,
        title: '列表操作',
        type: 'blank',
        difficulty: 'medium',
        points: 8
      },
      {
        id: 105,
        title: '函数定义',
        type: 'short',
        difficulty: 'medium',
        points: 12
      }
    ]
    
    autoGeneratedProblems.value = mockProblems.slice(0, autoSelectionForm.value.questionCount)
    ElMessage.success('题目生成成功！')
  } catch (error) {
    ElMessage.error('题目生成失败')
  } finally {
    generating.value = false
  }
}

// 工具函数：获取难度类型
const getDifficultyType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

// 工具函数：获取题目类型
const getQuestionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    choice: '单选题',
    blank: '填空题',
    short: '简答题',
    code: '编程题'
  }
  return typeMap[type] || type
}

// 工具函数：获取题目类型标签类型
const getQuestionTypeType = (type: string) => {
  const typeMap: Record<string, string> = {
    choice: 'primary',
    blank: 'warning',
    short: 'info',
    code: 'success'
  }
  return typeMap[type] || 'info'
}

onMounted(() => {
  loadAssignments()
  loadClasses()
  loadProblems()
  
  // 检查URL参数，如果是创建模式则显示创建对话框
  const urlParams = new URLSearchParams(window.location.search)
  if (urlParams.get('action') === 'create') {
    showCreateDialog.value = true
  }
})
</script>

<style scoped lang="scss">
.assignments-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
      color: #2c3e50;
      font-size: 1.8rem;
      font-weight: bold;
    }
  }
}

.assignments-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .empty-state {
    padding: 40px 0;
    text-align: center;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assignments-container {
    padding: 10px;
  }
  
  .header-card {
    .header-content {
      flex-direction: column;
      gap: 15px;
      align-items: stretch;
      
      h2 {
        text-align: center;
        font-size: 1.5rem;
      }
    }
  }
}

/* 作业布置对话框样式 */
.form-section {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  
  .section-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #2c3e50;
    
    .el-icon {
      color: #409eff;
    }
  }
}

.selection-content {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.problem-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.selected-problems {
  margin-top: 20px;
  
  h4 {
    margin: 0 0 15px 0;
    color: #2c3e50;
    font-size: 1rem;
  }
}

.auto-generated-preview {
  margin-top: 20px;
  
  h4 {
    margin: 0 0 15px 0;
    color: #2c3e50;
    font-size: 1rem;
  }
}

.form-tip {
  margin-top: 8px;
  font-size: 0.875rem;
  color: #909399;
  line-height: 1.4;
}

/* 题目选项样式 */
.el-select-dropdown__item {
  .problem-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }
}
</style>
